import json
from collections import defaultdict

json_path = "/home/guoyi/Dataset/aier_processed/annotations.json"
output_path = "lesion_stats.json"

with open(json_path, 'r') as f:
    annotations = json.load(f)

stats_per_image = defaultdict(lambda: defaultdict(list))
label_img_count = defaultdict(int)

for img_name, img_info in annotations.items():
    label = img_info["image_label"]
    label_img_count[label] += 1
    lesions = img_info["lesions"]
    lesion_counter = defaultdict(int)
    for lesion in lesions:
        lesion_name = lesion["name"]
        lesion_counter[lesion_name] += 1
    # 记录该图片每个病灶出现的次数
    for lesion_name in lesion_counter:
        stats_per_image[label][lesion_name].append(lesion_counter[lesion_name])
    # 对于没出现过的病灶补零
    for possible_lesion in set(stats_per_image[label].keys()) | set(lesion_counter.keys()):
        if possible_lesion not in lesion_counter:
            stats_per_image[label][possible_lesion].append(0)

result = {}
for label in stats_per_image:
    # 先计算出所有病灶的 avg, max, min，放入列表用于排序
    lesion_stats = []
    for lesion_name, counts in stats_per_image[label].items():
        avg = round(sum(counts) / len(counts), 3)
        mx = max(counts)
        mn = min(counts)
        lesion_stats.append((lesion_name, avg, mx, mn))
    # 按 avg 从高到低排序
    lesion_stats_sorted = sorted(lesion_stats, key=lambda x: x[1], reverse=True)
    # 构造字符串型结果
    result[label] = {}
    for lesion_name, avg, mx, mn in lesion_stats_sorted:
        stat_str = f"avg={avg}, max={mx}, min={mn}"
        result[label][lesion_name] = stat_str

with open(output_path, "w", encoding="utf-8") as f:
    json.dump(result, f, ensure_ascii=False, indent=2)

print(f"结果已写入 {output_path}")
